package cn.learn.office.excel_v2.sort;


import cn.learn.office.excel_v2.ExportExcelUtil;
import cn.learn.office.excel_v2.ExportExcelVo;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.List;
import java.util.Map;

/**
 * 处理table格式(二维数组)的Excel导出，测试了合并行，尚未做合并列
 *
 * @author huangyezhan
 * @version 2.0
 * @date 2020年4月20日21:16:41
 */
public class ArrayList4TableSort implements HandlerColumnSort {

    @Override
    public void columnSort(ExportExcelVo excelVo, Sheet sheet, Map<ExportExcelVo.Position, CellStyle> createStyleInstance) {
        List table = excelVo.getList();
        //开始导入数据开始行数号（去掉表头的行数）
        int              startRowNum = excelVo.getHeadRowNum();
        Row              row         = null;
        Cell             cell        = null;
        CellRangeAddress region      = null;
        for (int i = 0; i < table.size(); i++) {
            row = sheet.createRow(i + startRowNum);
            //处理列
            List columns = (List) table.get(i);
            for (int j = 0; j < excelVo.getColumnNum(); j++) {
                Map<String, Object> map     = (Map<String, Object>) columns.get(j);
                int                 rowspan = (int) map.get(excelVo.getRowspanName());
                if (rowspan > 1) {
                    // 合并日期占两行(4个参数，分别为起始行，结束行，起始列，结束列)
                    // 行和列都是从0开始计数，且起始结束都会合并
                    region = new CellRangeAddress(i + startRowNum, i + startRowNum + rowspan - 1, j, j);
                    sheet.addMergedRegion(region);
                }
                //根据列头名称获取数据
                if (rowspan > 0) {
                    Object o = map.get(excelVo.getHeadSort()[j]);
                    cell = row.createCell(j);
                    ExportExcelUtil.fillDatabyRealType(createStyleInstance, o, cell);
                }
            }
        }
    }


}
